#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>

#define  err_log(log) do{perror(log);}while(0)
#define  N  128

int main(int argc, const char *argv[])
{	
	int sockfd_parent;
    char buf_parent[N];
    char buf_info[N] = "nss send";
    struct sockaddr_in broadcastaddr_parent, srcaddr_parent;
	
	if((sockfd_parent = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
	{
	    err_log("recv: fail to socket");
	}

	broadcastaddr_parent.sin_family = AF_INET;
	broadcastaddr_parent.sin_addr.s_addr = inet_addr("172.18.20.255");
	broadcastaddr_parent.sin_port = htons(10000);

	if(bind(sockfd_parent, (struct sockaddr*)&broadcastaddr_parent, sizeof(broadcastaddr_parent)) < 0)
	{
	    err_log("recv: fail to bind");
	}

	socklen_t addrlen_parent = sizeof(struct sockaddr);

	while(1)
	{
	    if(recvfrom(sockfd_parent, buf_parent, N, 0, (struct sockaddr *)&srcaddr_parent, &addrlen_parent) < 0)
	    {
	        err_log("recv: fail to sendto");
	    }else{
	    	printf("buf:%s ---> %s %d\n", buf_parent, inet_ntoa(srcaddr_parent.sin_addr), ntohs(srcaddr_parent.sin_port));	
	    	if (strcmp(&buf_parent, &buf_info)==0){
				pid_t pid;
				pid = fork();
				//children process, used to send the reply to the client
				if (pid==0){
					int sockfd_children;
					struct sockaddr_in sockeaddr_children;
					char buf_children[N] = "receive ubuntu root";
					char shell_command[] = ". /home/ubuntu/dragon-stack/venv/bin/activate && python /home/ubuntu/dragon-stack/admins/join.py --host ";
					strcat(shell_command, inet_ntoa(srcaddr_parent.sin_addr));
					int optval = 1;
					if((sockfd_children = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
					{
						err_log("send: fail to socket");
					}

					sockeaddr_children.sin_family = AF_INET;
					sockeaddr_children.sin_addr.s_addr = inet_addr(inet_ntoa(srcaddr_parent.sin_addr));
					sockeaddr_children.sin_port = htons(10000);

					if(sendto(sockfd_children, buf_children, N, 0, (struct sockaddr *)&sockeaddr_children, sizeof(sockeaddr_children)) < 0)
					{
						err_log("send: fail to sendto");
					}else{
						err_log("send successful");
						system(shell_command);
					}

					}
				//fail to create the process
				else if (pid==-1){
					err_log("send: fail to create the send process");
				}
	    	}
	    }
	}

    return 0;
}
